package com.qf.work;

import com.qf.util.ConnUtil;
import com.rabbitmq.client.*;
import org.junit.Test;

import java.io.IOException;

/**
 * Work Queue
 */
public class Consumer {

    @Test   // 0.1
    public void consume1() throws Exception {
        //1. 获取connection对象
        Connection connection = ConnUtil.getConnection();

        //2. 创建Channel对象
        Channel channel = connection.createChannel();

        //3. 创建队列（队列名称，是否持久化，是否排外，自动删除，其他参数）
        channel.queueDeclare("work-queue",true,false,false,null);

        channel.basicQos(5);

        //4. 监听队列（队列名称，是否自动ack，回调函数）
        channel.basicConsume("work-queue",false,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消费者1号监听到消息：" + new String(body));
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });

        //5. System.in.read();
        System.in.read();
    }


    @Test   // 2
    public void consume2() throws Exception {
        //1. 获取connection对象
        Connection connection = ConnUtil.getConnection();

        //2. 创建Channel对象
        Channel channel = connection.createChannel();

        //3. 创建队列（队列名称，是否持久化，是否排外，自动删除，其他参数）
        channel.queueDeclare("work-queue",true,false,false,null);

        channel.basicQos(5);

        //4. 监听队列（队列名称，是否自动ack，回调函数）
        channel.basicConsume("work-queue",false,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消费者2号监听到消息：" + new String(body));
                System.out.println(envelope.getDeliveryTag());
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });

        //5. System.in.read();
        System.in.read();
    }
}
